<template>
  <div class="add-qrcode">
      <div class="container">
          <div class="code-title text-overflow">台码管理</div>
          <div class="code-container" v-loading="loading">
              
              <div class="filter-box">
                  <div>
                      <el-input v-model="filter.platformCode" placeholder="请输入台码"></el-input>
                  </div>
                  <div>
                      <el-input v-model="filter.agent" placeholder="请输入代理商手机"></el-input>
                  </div>
                  <div>
                      <el-input v-model="filter.shopPhone" placeholder="请输入商户手机"></el-input>
                  </div>
                  <div>
                      <el-date-picker style="width:140px" v-model="filter.staTime" value-format="yyyy-MM-dd HH:mm:ss" type="date" placeholder="开始日期"></el-date-picker>
                  </div>
                  <div>
                      <el-date-picker style="width:140px" v-model="filter.endTime" value-format="yyyy-MM-dd HH:mm:ss" type="date" placeholder="结束日期"></el-date-picker>
                  </div> 
                  <div>
                    <el-select v-model="filter.state" clearable >
                        <el-option v-for="item in stateList" :key="item.value" 
                            :value="item.value" :label="item.label"
                        ></el-option>
                    </el-select>
                  </div>
                  <div style="width:150px">
                    <el-button type="primary" @click="handleQuery" >筛选</el-button> 
                    <el-button @click="handleReset" >重置</el-button>
                  </div>  
              </div>

              <div class="code-list">
                  <el-table
                        ref="multipleTable"
                        :data="qrcodeList"
                        tooltip-effect="dark"
                        style="width: 100%"
                        @selection-change="handleSelectionChange">
                        <el-table-column
                            type="selection"
                            width="55">
                        </el-table-column>
                        <el-table-column
                            v-for="item in tableHeader" :key="item.prop"
                            :prop="item.prop"
                            :label="item.label"
                            :formatter="formatterList"
                            >
                        </el-table-column>
                        <el-table-column
                            fixed="right"
                            label="操作"
                            width="150">
                            <template slot-scope="scope">
                                <el-button @click="handleLookcode(scope.row)" type="text">查看</el-button>
                                <el-button @click="handleActived(scope.row)" type="text">激活</el-button>
                                <el-button @click="handleBindcode(scope.row)" type="text">绑定</el-button>
                            </template>
                        </el-table-column>
                    </el-table>
              </div>
              <div class="operate-box">
                  <el-button @click="handleExportExcel">导出Excel表格</el-button>
              </div>
            <div class="pages-control">
                <el-pagination
                    @current-change="handleCurrentChange"
                    :current-page.sync="pages.currentPage"
                    :page-size="pages.page_size"
                    layout="total, prev, pager, next"
                    :total="pages.total">
                </el-pagination>
            </div>
             

          </div>  
      </div>
    <!-- 查看dailog -->
    <el-dialog
        title="查看台码"
        :visible.sync="dialogVisible2"
        width="600px">
        <div style="text-align:center">
            <img width="350px" height="350px" :src="previewCodeUrl" alt="台码加载失败！" />
        </div>
        <div style="text-align:center" >
            <span v-html="previewCode"></span>
        </div>
        <span slot="footer" class="dialog-footer"> 
            <el-button style="width:100px"  type="primary" @click="handleDownloadQrcode">下 载</el-button>
            <el-button style="width:100px"   @click="dialogVisible2 = false">取 消</el-button>
        </span>
    </el-dialog>
    <!-- 激活dailog -->
    <el-dialog
        title="激活台码"
        :visible.sync="dialogVisible"
        width="50%">
       
        <div class="">
            <span>台码：</span><span v-html="activeInfo.platformCode"></span>
        </div>
        <br />
        <div class="">
            <span>代理商手机号：</span><span v-html="activeInfo.agent"></span>
        </div>
        <br />
        <div class="">
            <span>商户手机号：</span><span v-html="activeInfo.shopId"></span>
        </div>
        <br />
        <div>
            <span>推广人手机号：</span><span v-html="activeInfo.introducerPhone"></span>
        </div>
        <br />
        <span slot="footer" class="dialog-footer"> 
            <el-button type="primary" @click="submitActiveCode">确 定</el-button>
            <el-button @click="dialogVisible = false">取 消</el-button>
        </span>
    </el-dialog>
    <!-- 绑定dailog -->
    <el-dialog
        title="绑定商户"
        :visible.sync="dialogVisible1"
        width="50%">
        <!-- <div>
             {{bindInfo}}
        </div> -->
       
        <div class="">
            <span>台码：</span><el-input v-model="bindInfo.platformCode" disabled></el-input>
        </div>
        <div class="">
           <span>代理商手机号：</span> <el-input v-model="bindInfo.agent" disabled></el-input>
        </div>
        <div class="">
            <span>商户手机号：</span> <el-input v-model="bindInfo.merchantId" @blur="handleQueryShop" placeholder="请输入需要绑定的商户手机号"></el-input>
        </div>
        <div>
            <span>商户名称：</span><span v-html="bindInfo.bindShop"></span>
        </div>
        <div>
            <span>推广人手机号：</span><el-input v-model="bindInfo.introducerPhone"></el-input>
        </div>


        <span slot="footer" class="dialog-footer"> 
            <el-button type="primary" @click="submitBindCode">确 认 绑 定</el-button>
            <el-button @click="dialogVisible1 = false">取 消 绑 定</el-button>
        </span>
    </el-dialog>
      <!-- 导出excel -->
     <el-dialog
        title="导出表格"
        :visible.sync="dialogVisible3"
        width="50%">
        
        <div>
            <span>导出方式</span>
            <el-select v-model="exportInfo.type" >
                <el-option v-for="item in exportTypes" :key="item.value" 
                    :value="item.value" :label="item.label"
                ></el-option>
            </el-select>
        </div>
 
        <span slot="footer" class="dialog-footer"> 
            <el-button type="primary" @click="handleSubmitExport">确 定</el-button>
            <el-button @click="dialogVisible3 = false">取 消</el-button>
        </span>
    </el-dialog>
  </div>
</template>

<script>
function download(url, name) {
    const aLink = document.createElement('a')
    aLink.download = name 
    aLink.href = url 
    aLink.dispatchEvent(new MouseEvent('click', {}))
}

export default {
  name:'add-qrcode',
  data () {
    return {
        loading:false,
        allcheck:false,
        dialogVisible:false,
        dialogVisible1:false,
        dialogVisible2:false,
        dialogVisible3:false,
        previewCodeUrl:"",
        previewCode:"",
        selectedList:[],
        exportTypes:[
            {value:"0",label:"条件导出"},
            {value:"1",label:"勾选导出"}
        ],
        stateList:[
            {label:"未绑定",value:"0"},
            {label:"未激活",value:"1"},
            {label:"已激活",value:"2"}
        ],
        activeInfo:{
            platformCode:"",
            bindShop:"",
            agent:"",
            shopId:"",
            introducerPhone:""
        },
        bindInfo:{
            platformCode:"",
            bindShop:"",
            agent:"",
            merchantId:"",
            platformType:"",
            introducerPhone:""
        },
        filter:{
            platformCode:'',
            agent:'', // 手机号
            staTime:'',
            endTime:'',
            state:"",
            shopPhone:'', // 商户手机号
        },
        exportInfo:{
            type:0, // 0 条件  1 勾选
        },
        qrcodeList:[],
        tableHeader:[
            {prop:'platformCode',label:'台卡卡号',width:140},
            {prop:'platformType',label:'卡片类型',width:100},
            {prop:'agent',label:'所属代理商',width:140},
            {prop:'shopId',label:'所属商户',width:140},
            {prop:'dialCodeType',label:'拨码状态',width:140},
            {prop:'state',label:'状态',width:140},
            {prop:'createTime',label:'创建时间',width:160},
            {prop:'createBy',label:'创建人',width:140},
        ],
        pages:{
          total:10,
          page_size:20,
          currentPage:1
        }
    };
  },
  created() {this.handleQuery()},
  mounted() {},
  methods: {
      handleSelectionChange(val){
          this.selectedList = val;
      },
      handleFileChange(file){
          console.log(file);
      },
      handleCurrentChange(value){
           this.handleQuery();
      },
      handleDownloadQrcode(){
          // 下载
          let name = this.previewCode+".jpg";
          download(this.previewCodeUrl,name);
      },
      handleStatus(status){
          if(status==='0'){
              return "未绑定";
          }
          if(status==='1'){
              return "未激活";
          }
          if(status==='2'){
              return "已激活";
          }
          return status;
      },
      handleLookcode(cell){
          this.dialogVisible2 = true;
          this.previewCodeUrl = cell.qrcCode;
          this.previewCode = cell.platformCode;
      },
      handleQuery(){
           let token = sessionStorage.getItem(1);
          let url = `user/app/Platform/queryPlatformPagerlist/${token}?pageNumber=${this.pages.currentPage}`;
          for(let key in this.filter){
              if(this.filter[key]!==undefined && this.filter[key]!==null && this.filter[key]!==''){
                  url += `&${key}=${this.filter[key]}`
              }
          }
          url=encodeURI(url);
          this.loading = true;
          this.$Http.get(url,'').then(res=>{
              this.loading = false;
              if(res.data.resp_code === "000000"){
                this.pages.total = res.data.count;
                this.qrcodeList = res.data.result;
              }else{
                  this.$notify({
                        title: '温馨提示',
                        message: res.data.resp_message,
                        type: 'warning'
                  });
              }
          }).catch(err=>{
              this.loading = false;
                this.$notify({
                        title: '温馨提示',
                        message: "获取台卡列表失败！",
                        type: 'warning'
                });
          })

      },
      handleReset(){
           for(let key in this.filter){
               this.filter[key] = ''
           }
           this.handleQuery();
      },
      handleActived(cell){
          if(cell.state === '2'){
               this.$notify({
                    title: '温馨提示',
                    message: "该台卡已经激活过了！",
                    type: 'warning'
                });
              return;
          }

          if(cell.dialCodeType === '0'){
              this.$notify({
                    title: '温馨提示',
                    message: "该台卡未拨码！无法激活！",
                    type: 'warning'
                });
              return;
          }

        if(cell.state !=='1'){
              this.$notify({
                    title: '温馨提示',
                    message: "该台卡未绑定商户！无法激活！",
                    type: 'warning'
                });
              return;
        }
    
        this.activeInfo.agent = cell.agent;
        this.activeInfo.platformCode = cell.platformCode;
        this.activeInfo.platformType = cell.platformType;
        this.activeInfo.shopId = cell.shopId;
        this.activeInfo.introducerPhone = cell.introducerPhone;
        
        // TODO 获取
        this.dialogVisible = true;
      },
      handleQueryShop(e){
        //   console.log(e.target.value);
         let url = `user/shop/findByMobilePhone?mobilePhone=${e.target.value}`;
         this.$Http.get(url).then(res=>{
             if(res.data.resp_code==="000000"){
                 this.bindInfo.bindShop = res.data.result.shopName;
             }else{
                 this.$notify({
                    title: '温馨提示',
                    message: res.data.resp_message,
                    type: 'warning'
                });
             }
         }).catch(err=>{
             this.message.error("查询商户信息失败！")
         })
      },
      handleBindcode(cell){
          // 弹出dailog
          if(cell.state === '2'){
               this.$notify({
                    title: '温馨提示',
                    message: "该台卡已经激活过了！",
                    type: 'warning'
                });
              return;
          }

          if(cell.dialCodeType === '0'){
              this.$notify({
                    title: '温馨提示',
                    message: "该台卡未拨码！无法绑定！",
                    type: 'warning'
                });
              return;
          }
    
        this.bindInfo.agent = cell.agent;
        this.bindInfo.platformCode = cell.platformCode;
        this.bindInfo.platformType = cell.platformType;
        this.bindInfo.merchantId = cell.shopId;
        // TODO 获取
        this.dialogVisible1 = true;
      },
      submitBindCode(){
          // 提交绑定信息
          if(this.bindInfo.introducerPhone === ''){
              this.$notify({
                title: '温馨提示',
                message: "请输入推广人！",
                type: 'warning'
            });
              return;
          }
           let token = sessionStorage.getItem(1);
          let url = `user/app/Platform/binding/${token}`;
          let params = `type=1&platformType=${this.bindInfo.platformType}&platformCode=${this.bindInfo.platformCode}&merchantId=${this.bindInfo.merchantId}&introducerPhone=${this.bindInfo.introducerPhone}`;
          this.$Http.post(url,params).then((res) => {
              if(res.data.resp_code === "000000"){
                this.$notify({
                    title: '温馨提示',
                    message: "绑定成功！",
                    type: 'success'
                }); 
                this.dialogVisible1 = false;
                this.handleQuery();
             }else{
                 this.$notify({
                    title: '温馨提示',
                    message: res.data.resp_message,
                    type: 'warning'
                });
             }
          }).catch((err) => {
              this.$notify({
                    title: '温馨提示',
                    message: "服务器繁忙！绑定失败！",
                    type: 'warning'
                });
          });
      },
      handleExport(){
          if( this.selectedList.length ===0){
              this.$notify({
                    title: '温馨提示',
                    message: "请至少选择一条数据导出！",
                    type: 'warning'
                });
              return;
          }
          let dialCode = this.selectedList.map(item=>item.platformCode).join(',');
          let token = sessionStorage.getItem(1);
          let url = `user/app/Platform/exportImg/${token}`;
          let params = `dialCode=${dialCode}`;
          this.$Http.post(url,params,{
               responseType: 'blob'
          }).then(res=>{
            let blob = res.data
            let reader = new FileReader()
            reader.readAsDataURL(blob)
            reader.onload = (e) => {

                let a = document.createElement('a')
                a.download = "codes.zip"
                a.href = e.target.result
                document.body.appendChild(a)
                a.click()
                document.body.removeChild(a)
            }
          }).catch(err=>{
              this.$notify({
                    title: '温馨提示',
                    message: "导出信息失败！",
                    type: 'warning'
                });
          })

      },
      handleSubmitExport(){
          // 导出操作
          this.dialogVisible3 = false;
          let arrType = this.exportInfo.type;
          let arrCode = this.selectedList.map(item=>item.platformCode).join(',');
         
          let token = sessionStorage.getItem(1);
          let url = `user/app/Platform/export/${token}`;
          let params = `platformCode=${platformCode}&arrType=${arrType}&arrCode=${arrCode}`;
          for(let key in this.filter){
              if(this.filter[key]!==undefined && this.filter[key]!==null && this.filter[key]!==''){
                  url += `&${key}=${this.filter[key]}`
              }
          }
          params = encodeURI(params);
          this.$Http.post(url,params,{
            responseType: 'blob'
          }).then(res=>{
            //   this.$Http.download(res);
            let blob = res.data
            let reader = new FileReader()
            reader.readAsDataURL(blob)
            reader.onload = (e) => {
                let a = document.createElement('a')
                a.download = "info.xlsx"
                a.href = e.target.result
                document.body.appendChild(a)
                a.click()
                document.body.removeChild(a)
            }
          }).catch(err=>{
              this.$notify({
                    title: '温馨提示',
                    message: "导出信息失败！",
                    type: 'warning'
                });
          })
      },
       handleExportExcel(){
          // 导出excel
         this.dialogVisible3 = true;
      },
      submitActiveCode(){
          // 提交激活操作
          let token = sessionStorage.getItem(1);
          let url = `user/app/Platform/binding/${token}`;
          let params = `type=2&platformType=${this.activeInfo.platformType}&platformCode=${this.activeInfo.platformCode}&agent=${this.activeInfo.agent}&merchantId=${this.activeInfo.shopId}&introducerPhone=${this.activeInfo.introducerPhone}`;
          this.$Http.post(url,params).then((res) => {
             if(res.data.resp_code === "000000"){
                this.$notify({
                    title: '温馨提示',
                    message: "激活成功！",
                    type: 'success'
                }); 
                this.dialogVisible = false;
                this.handleQuery();
             }else{
                 this.$notify({
                    title: '温馨提示',
                    message: res.data.resp_message,
                    type: 'warning'
                });
             }
          }).catch((err) => {
              this.$notify({
                    title: '温馨提示',
                    message: "服务器繁忙！激活失败！",
                    type: 'warning'
                });
          });
      },
      formatterList(row, column, cellValue, index) {
      //  格式化信息
      if (column.property === "platformType") {
        return cellValue == "1" ? "台卡" : "其他类型";
      } else if (column.property === "agent") {
        return cellValue ? cellValue : "暂无代理";
      } else if (column.property === "shopId") {
        return cellValue ? cellValue : "暂无商户";
      } else if (column.property === "dialCodeType") {
        return cellValue === "0" ? "未拨码" : "已拨码";
      } else if (column.property === "dialCodeType") {
        return cellValue === "0" ? "未拨码" : "已拨码";
      } else if (column.property === "state") {
        return this.handleStatus(cellValue);
      } else {
        return cellValue===null?'--':cellValue;
      }
    }
  }
}

</script>
<style scoped>
.container{
  border: 1px solid #ededed;
}
.code-title{
  height: 50px;
  line-height: 50px;
  font-size: 26px;
  color: #409eff;
  padding: 5px 20px;
  border-bottom: 1px solid #ededed;
}

.filter-box{
    padding: 20px ;
    display: flex;
    justify-content: space-around;
    border-bottom: 1px solid #efefef;
}
.filter-box>div{
    width: 160px;
    box-sizing: border-box;
    padding: 0 10px;
}
.code-list{
       min-height: 350px;
}
table{
    background-color: #FFF;
    width: 100%;
    font-size: 12px;
    min-width: 900px;
}
th{
    position: relative;
    word-wrap: normal;
    text-overflow: ellipsis;
    vertical-align: middle;
    border-bottom: 1px solid #ebeef5;
    
}
thead{
    padding: 8px 0;
    color: #909399;
    background-color: #F5F7FA;
}
tr{
    padding: 8px 0;
}
tr:hover{
    background-color: #ccd2df;
}
td{
    border: none;
    border-bottom: 1px solid #ebeef5;
}
.table-cell{
    white-space: normal;
    word-break: break-all;
    line-height: 22px;
    padding: 10px 10px;
    text-align: center;
    min-width: 40px;
    box-sizing: border-box;
}
.pages-control{
    display: flex;
    justify-content: center;
    align-items: center;
    height: 40px;
    border-top:1px solid #ebeef5;
}
.code-activated{
    background-color: #F5F7FA;
}
.operate-box{
    padding: 16px;
}
</style>